package com.four.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.four.user.config.JwtUtil;
import com.four.user.config.MsgUtil;
import com.four.user.dao.UserDao;
import com.four.user.entity.User;
import com.four.user.service.UserService;
import com.guli.common.utils.R;
import com.guli.common.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @Author:wsy
 * @Date: 2021/12/16/13:33
 * @Description
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public R login(String userPhone, String code) {
        //查询是否有该电话号码
        User phone =userDao.selectByPhone(userPhone);
        if (phone!=null){
            //判断输入的验证码与发送到手机的验证码是否相同
            String yzm = redisTemplate.opsForValue().get(userPhone);
            if (code.equals(yzm)){
                //生成令牌
                String token = jwtUtil.createJwt(userPhone.toString(), code,"user");
                System.out.println(token);
                return R.ok().put("token",token).put("userPhone",userPhone);
            }
        }
        return R.error();
    }

    @Override
    public R sendMsg(String userPhone) {
        //先用手机号发送短信，获取验证码
        String s = MsgUtil.sendMsg(userPhone);
        System.out.println(s);
        //将验证码存入redis，1分钟过期
        redisTemplate.opsForValue().set(userPhone,s,60, TimeUnit.SECONDS);
        return R.ok().put("msg",s);
    }

    /**
     * 根据登录人名查询
     * @param loginName
     * @return
     */
    @Override
    public User findByUname(String loginName) {
        return userDao.findByUname(loginName);
    }

    @Override
    public UserVo getUserById(Integer userId) {
        return userDao.getUserById(userId);
    }
}
